package com.webchat.aigc.controller;

import com.webchat.common.bean.APIResponseBean;
import com.webchat.common.bean.APIResponseBeanUtil;
import com.webchat.common.enums.PromptTemplateEnum;
import com.webchat.common.service.FreeMarkEngineService;
import com.webchat.common.util.FreemarkerUtils;
import com.webchat.domain.dto.aigc.mall.MallAutoReplayReqDTO;
import com.webchat.domain.vo.dto.mall.im.AIGCRecommendAnswerReqDTO;
import com.webchat.rmi.aigc.AIMallServiceClient;
import freemarker.template.TemplateException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
public class AIMallServiceController implements AIMallServiceClient {

    @Autowired
    private ChatModel deepSeekChatModel;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

    @Override
    public APIResponseBean<String> aiAutoReply(@RequestBody MallAutoReplayReqDTO mallAutoReplayReq) {
        response.setCharacterEncoding("UTF-8");
        // TODO 临时简单实现，等RAG完成后打通
        Map<String, Object> vars = new HashMap<>();
        vars.put("shopName", mallAutoReplayReq.getShopName());
        vars.put("content", "暂无参考内容～");
        vars.put("username", mallAutoReplayReq.getUsername());
        vars.put("userMessages", mallAutoReplayReq.getUserMessages());
        String input = null;
        try {
            input = freeMarkEngineService.getContentByTemplate(PromptTemplateEnum.MALL_AI_AUTO_REPLAY.getPath(), vars);
        } catch (Exception e) {
            // TODO
            log.error("商家智能客服AI代发Prompt模版渲染失败 ===> vars:{}", vars, e);
            return APIResponseBeanUtil.success(null);
        }

        String response =  ChatClient.builder(deepSeekChatModel).build().prompt()
                .user(input)
                .call()
                .content();
        return APIResponseBeanUtil.success(response);
    }

    @Override
    public Flux<String> recommendAnswers(AIGCRecommendAnswerReqDTO aigcRecommendAnswerReqDTO) {

        response.setCharacterEncoding("UTF-8");
        Map<String, Object> vars = new HashMap<>();
        vars.put("shopName", aigcRecommendAnswerReqDTO.getShopName());
        // TODO 后续接入店铺知识库RAG检索能力
        vars.put("content", "暂无参考内容～");
        vars.put("recommendSize", aigcRecommendAnswerReqDTO.getRecommendSize());
        vars.put("historyMessages", aigcRecommendAnswerReqDTO.getHistoryMessages());
        vars.put("waitRelyMessages", aigcRecommendAnswerReqDTO.getWaitRelyMessages());
        String queryPrompt = null;
        try {
            queryPrompt = freeMarkEngineService.getContentByTemplate(PromptTemplateEnum.MALL_RECOMMEND_ANSWER.getPath(), vars);
        } catch (Exception e) {
            // TODO
            log.error("商家智能客服AI代发Prompt模版渲染失败 ===> vars:{}", vars, e);
            return Flux.empty().map(String::valueOf).concatWithValues("模型处理失败！");
        }
        var prompt = new Prompt(new UserMessage(queryPrompt));
        return deepSeekChatModel.stream(prompt).map(resp -> {
            Generation generation = resp.getResult();
            if (generation != null &&
                    generation.getOutput() != null) {
                return generation.getOutput().getText();
            }
            return "";
        });
    }
}
